package com.caption.mq.config;

import com.caption.mq.core.MqUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;


/**
 * @description: TODO
 * @author: 码农
 * @date: 2022-01-16 17:32:41
 */
@Configuration
@Slf4j
@ConditionalOnBean(BaseMqAutoConfiguration.class)
public class MqProductAutoConfiguration extends BaseMqAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(DefaultMQProducer.class)
    public DefaultMQProducer defaultMQProducer() throws MQClientException {
        String nameServer = mqProperties.getNameServer();
        String groupName = mqProperties.getProductGroup();
        Assert.hasText(nameServer, "[rocketmq.name-server] must not be null");
        Assert.hasText(groupName, "[rocketmq.producer.group] must not be null");
        DefaultMQProducer producer = new DefaultMQProducer(groupName);
        producer.setNamesrvAddr(nameServer);
        if (mqProperties.getSendMsgTimeout() != null) {
            producer.setSendMsgTimeout(mqProperties.getSendMsgTimeout());
        }
        producer.start();
        return producer;
    }


    @Bean
    @ConditionalOnBean(DefaultMQProducer.class)
    public MqUtils mqUtils(DefaultMQProducer mqProducer) {
        MqUtils mqUtils = new MqUtils();
        mqUtils.setDefaultMQProducer(mqProducer);
        return mqUtils;
    }

}
